﻿using System;
using Microsoft.SharePoint;

namespace Demo.SharePoint.WebParts.OfficeLocator
{
    public class OfficeSearch
    {
        /// <summary>
        /// Searches for offices given the specified query and radius.
        /// </summary>
        /// <param name="query">The query.</param>
        /// <param name="radius">The radius.</param>
        /// <param name="listUrl">The list url to search.</param>
        /// <returns></returns>
        public static SPListItemCollection Search(string query, double? radius, string listUrl)
        {
            if (String.IsNullOrEmpty(query) || String.IsNullOrEmpty(listUrl))
                return null;

            SPList list = GetOfficeList(listUrl);
            if (list == null)
                return null;

            SPListItemCollection offices;

            // Try to convert query to int to see if its a zip code
            int zip;
            if (int.TryParse(query, out zip))
            {
                // Make sure its not longer than 5
                zip = query.Length > 5 ? Convert.ToInt32(query.Substring(0, 5)) : zip;
                offices = FindOfficesByZip(zip, radius, list);
            }
            else
            {
                offices = FindOfficesByPlace(query, radius, list);
            }

            return offices;
        }

        private static SPListItemCollection FindOfficesByZip(int zip, double? radius, SPList list)
        {
            SPQuery qry = new SPQuery();
            // BeginsWith or Contains? - going to use BeginsWith for now
            qry.Query = "<Where><Contains><FieldRef Name='WorkZip' /><Value Type='Text'>" + zip + "</Value></BeginsWith></Where><OrderBy><FieldRef Name='Title' Ascending='True' /></OrderBy>";
            SPListItemCollection offices = list.GetItems(qry);
            return offices;
        }

        private static SPListItemCollection FindOfficesByPlace(string query, double? radius, SPList list)
        {
            SPQuery qry = new SPQuery();
            // BeginsWith or Contains? - going to use BeginsWith for now
            qry.Query = "<Where><Contains><FieldRef Name='WorkCity' /><Value Type='Text'>" + query + "</Value></BeginsWith></Where><OrderBy><FieldRef Name='Title' Ascending='True' /></OrderBy>";
            SPListItemCollection offices = list.GetItems(qry);
            return offices;
        }

        public static SPList GetOfficeList(string listUrl)
        {
            try
            {
                using (SPSite site = new SPSite(listUrl))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        return web.GetList(listUrl);
                    }
                }
            }
            catch (Exception)
            {
                return null;
            }
        }
    }
}